package cn.com.tpqn;

import com.elite.groovy.kh.KHDBConfig;
import com.elite.groovy.kh.KHUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.jdbc.core.JdbcTemplate;

import java.io.IOException;

public class sessionDetailRecord {
    private static final Log log = LogFactory.getLog(sessionDetailRecord.class);
    private static JSONObject rec_Config = new JSONObject();

    public static String CCODURL = "";
    public static String Secret_Key = "";
    public static String Secret_Id = "";
    public static String EntID = "";
    public static String ProxyIP = "";
    public static String ProxyPort = "";

    private static String resultInfo = "";

    public static String main(JdbcTemplate jt, String sessionId, String multiMode) {

        // 初始化参数
        EntID = "1909090002";
        rec_Config = KHUtil.SFIsNull(rec_Config.toString()) ? net.sf.json.JSONObject.fromObject(KHDBConfig.getParamConfig(jt, "REC_CFG-" + EntID)) : rec_Config;

        CCODURL = KHUtil.GetSFJV(rec_Config, "CCODURL");

        Secret_Key = KHUtil.GetSFJV(rec_Config, "SECRET_KEY");
        Secret_Id = KHUtil.GetSFJV(rec_Config, "SECRET_ID");
        ProxyIP = KHUtil.GetSFJV(rec_Config, "ProxyIP");
        ProxyPort = KHUtil.GetSFJV(rec_Config, "ProxyPort");

        CloseableHttpClient httpclient = null;
        try {
            long currentTime = System.currentTimeMillis();
            String authorization = "/customWebservice/mvc/sessionDetail/queryRecord.do?Nonce=" + currentTime + "&Timestamp=" + currentTime / 1000 + "&SecretId=" + Secret_Id;
            log.debug("鉴权认证信息:" + authorization);

            String Signature = QnSignUitl.sign(authorization, Secret_Key);
            log.debug("调用接口秘钥信息:" + Signature);

            String URI = CCODURL + "/customWebservice/mvc/sessionDetail/queryRecord.do?entId=" + EntID + "&sessionId=" + sessionId + "&pageNum=1&Signature=" + Signature;
            log.debug("调用的接口地址信息:" + URI);

            if ((ProxyIP == null) || (ProxyIP.length() <= 0)) {
                httpclient = HttpClients.createDefault();
                log.debug("直接访问调用...");
            } else {
                HttpHost proxy = new HttpHost(ProxyIP, Integer.parseInt(ProxyPort), "http");

                RequestConfig defaultRequestConfig = RequestConfig.custom().setProxy(proxy).build();

                httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
                log.debug("代理访问调用...");
            }

            HttpPost httpPost = new HttpPost(URI);
            httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
            httpPost.setHeader("Accept", "*/*");
            httpPost.setHeader("Authorization", authorization);

            CloseableHttpResponse response2 = httpclient.execute(httpPost);
            try {
                log.debug(response2.getStatusLine());
                log.debug(response2.getEntity().getContentType());
                HttpEntity entity2 = response2.getEntity();
                resultInfo = EntityUtils.toString(entity2, "UTF-8");
            } finally {
                response2.close();
            }
        } catch (Exception e) {
            log.error("sessionDetailRecord 出现异常", e);

        } finally {
            try {
                assert httpclient != null;
                httpclient.close();
            } catch (IOException e) {
                log.warn("httpclient连接释放异常警告");
            }
        }

        log.debug("平台接口返回信息:" + resultInfo);
        System.out.println("平台接口返回信息:" + resultInfo);
        if ((resultInfo != null) && (resultInfo.length() > 0))
            try {
                JSONObject reJsObject = JSONObject.fromObject(resultInfo);
                String code = reJsObject.getString("code");
                log.debug("平台接口返回code:" + code);

                if (code.equals("0")) {
                    JSONArray dataArray = reJsObject.getJSONArray("result");
                    int dataArrayLen = dataArray.size();

                    log.info("平台接口返回 Result size:" + dataArrayLen);

                    // multiMode: 空 需转码->文件流 无需转码->重定向 0原始Json 1封装XML返回
                    if ((KHUtil.isNull(multiMode)) && (dataArrayLen == 1)) {
                        resultInfo = KHUtil.GetSFJV(dataArray.getJSONObject(0), "recordName");
                    } else if (multiMode.equals("0")) {
                        resultInfo = resultInfo;
                    } else {
                        JSONObject dataObject = null;
                        String recordName = null;

                        String recordList = "";
                        for (int i = 0; i < dataArrayLen; i++) {
                            dataObject = dataArray.getJSONObject(i);
                            recordName = KHUtil.GetSFJV(dataObject, "recordName");

                            recordList = recordList + "<recordName>" + recordName + "</recordName>";
                        }

                        resultInfo = "<recordFiles><recordFile>" + recordList + "</recordFile></recordFiles>";
                    }
                } else {
                    resultInfo = "<recordFiles><recordFile><recordName>" + code + "</recordName></recordFile></recordFiles>";
                }
            } catch (Exception e) {
                resultInfo = "<recordFiles><recordFile>" + e.getMessage() + "</recordFile></recordFiles>";
                log.error("sessionDetailRecord 出现异常", e);
            }
        else {
            resultInfo = "<recordFiles><recordFile><recordName></recordName></recordFile></recordFiles>";
        }
        return resultInfo;
    }
}